<template>
	<div class="shopbag">
		<div class="shopbag-ad">
			<img :src="require('@/assets/images/shopbag_bg.png')" alt="广告图">
		</div>
		<div class="shopbag-box" v-if="shopCartData.length">
			<div class="shopbag-item"
				v-for="(item,index) in shopCartData"
				:key="index"
			>
				<van-swipe-cell :disabled="!isEdit">
					<!-- 右侧滑块 -->
					<template #right>
						<van-button square type="danger" text="删除" class="delete-button" @click="removeOne(index,item.sid)" />
					</template>
					<!-- 选中按钮 -->
					<div class="check-box">
						<van-checkbox v-model="item.isChecked" checked-color="#3498db" @click="simpleSelect" />
					</div>
					<!-- 自定义卡片 -->
					<van-card
						lazy-load
						:price="item.price"
						:title="item.name"
						:desc="item.rule"
						:thumb="item.small_img"
					>
						<!-- 标签 -->
						<template #tags>
							<van-tag plain type="danger">{{item.type_desc}}</van-tag>
						</template>
						<!-- 数量 -->
						<template #footer>
							<van-stepper
								v-model="item.count"
								disable-input
								@change="changeCount(item)"
							 />
						</template>
					</van-card>
				</van-swipe-cell>
			</div>
				
			<!-- 提交 -->
			<van-submit-bar 
				v-if="!isEdit"	
				:price="total" 
				button-text="提交订单" 
				@submit="commit" 
			>
				<van-checkbox v-model="isAllCheck" @click="allSelect">全选</van-checkbox>
			</van-submit-bar>
			
			<!-- 删除 -->
			<van-submit-bar 
				v-else 
				button-text="删除商品" 
				@submit="removeSelected">
				<van-checkbox v-model="isAllCheck" @click="allSelect">全选</van-checkbox>
			</van-submit-bar>
		</div>
		<van-empty description="暂时没有热门推荐,去逛一下其他的吧!" v-else />
	</div>
</template>

<script>
	import bus from '@/utils/eventBus.js'
	import { 
		getShopCart,
		removeShopCart,
		changeSCC
	 } from '@/api/order.js'
	export default {
		data () {
			return {
				isEdit: null, // 是否处于编辑状态
				shopCartData: [],  //	购物车数据数组
				isAllCheck: false, //	全选
				total: 0 //	选中价格
			}
		},
		created() {
			this._getShopCart()
			// 购物车头部组件通知 （是否为编辑）
			bus.$on('isEdit', (isEdit) => {
				this.isEdit = isEdit
			})
			// 商品详情立即购买以及加入购物车按钮通知,pay页面提交订单组件通知 （刷新购物车数据）
			bus.$on('refresh-shop-cart', () => {
				this._getShopCart()
			})
			
		},
		methods: {
			// 获取购物车数据
			_getShopCart() {
				const tokenString = window.sessionStorage.getItem('token')
				if (!tokenString) return this.$router.push({name: 'Login'})
				this.$toast.loading({
					message: '加载中···',
					forbidClick: true
				})
				getShopCart({
					tokenString
				})
				.then(({data: res}) => {
					if (res.code !== 5000) return this.$toast.fail('请求异常,请重新尝试!')
					this.$toast.clear()
					console.log('我的购物车商品',res)
					// 给返回的数据添加响应式数据
					res.result.forEach(item => {
						this.$set(item, 'isChecked', false)
					})
					this.shopCartData = res.result
				})
				.catch(err => {
					this.$toast.fail('请求失败,请重新尝试!')
				})
			},
			// 计算全中商品价格
			sum() {
				let sum = 0
				// 遍历计算价格
				this.shopCartData.forEach(item => {
					if (!item.isChecked) return
					sum += item.count * item.price
				})
				this.total = sum * 100
			},
			// 删除单个购物车商品
			async removeOne(index,sid) {
				const tokenString = window.sessionStorage.getItem('token')
				if (!tokenString) return this.$router.push({ name: "Login" })
				// 提示框
				const resultConfirm = await this.$dialog.confirm({
					message: '确认删除?'
				}).catch(err => err)
				// 判断是否点击确定
				if (resultConfirm !== 'confirm') return this.$toast('取消删除')
				// 加载
				this.$toast.loading({
					message: '删除中···',
					forbidClick: true
				})
				// 请求数据需要转换为字符串数组
				let sids = JSON.stringify([sid])
				// 发起请求
				removeShopCart({
					tokenString,
					sids
				})
				.then(({data: res}) => {
					console.log('删除单个购物车商品',res)
					if (res.code !== 7000) return this.$toast.fail('请求异常,请重新尝试!')
					this.$toast.success(res.msg)
					// 从原数组中删除
					this.shopCartData.splice(index, 1)
				})
				.catch(err => {
					this.$toast.fail('请求失败,请重新尝试!')
				})
			},
			// 单选
			simpleSelect() {
				this.sum()
				// 遍历判断购物车是否有没有选中的状态
				for (let i in this.shopCartData) {
					if (!this.shopCartData[i].isChecked) return this.isAllCheck = false
				}
				this.isAllCheck = true
			},
			// 全选
			allSelect() {
				// 遍历
				this.shopCartData.forEach(item => {
					item.isChecked = this.isAllCheck
				})
				this.sum()
			},
			// 改变商品数量请求
			changeCount(item) {
				const tokenString = window.sessionStorage.getItem('token')
				if (!tokenString) return this.$router.push({ name: "Login" })
				// 发送请求
				changeSCC({
					tokenString,
					sid: item.sid,
					count: item.count
				})
				.then(({data:res}) => {
					console.log('改变数量',res)
					if (res.code !== 6000) {
						this.$toast.fail('请求异常,请重新尝试!')
						return 
					}
					// 节省带宽 选中情况下调用
					if(item.isChecked) return this.sum()
				})
				.catch(err => {
					this.$toast.fail('请求失败,请重新尝试!')
				})
			},
			// 提交订单
			commit() {
				let isHas = this._isHas()
				if (!isHas) return
				let sids = []
				// 遍历获取选中的 sid
				this.shopCartData.forEach(item => {
					if (item.isChecked) return sids.push(item.sid)
				})
				sids = sids.join('-')
				this.$router.push({ name: "Pay", query: {sids} })
			},
			// 删除选中购物车商品
			removeSelected() {
				console.log('removeSelected')
			},
			// 是否有选中
			_isHas () {
				let flag = false
				this.shopCartData.forEach(item => {
					if (item.isChecked) 
						flag = true
				})
				return flag
			}
		}
	}
</script>

<style lang="scss" scoped>
	.shopbag{
		.shopbag-ad{
			margin: 5px 0;
			img {
				width: 100%;
			}
		}
		.shopbag-box{
			padding-bottom: 40px;
			.shopbag-item{
				margin: 8px 10px;
				/deep/ .van-swipe-cell{
					border-radius: 10px;
					.check-box{
						position: absolute;
						z-index: 99;
						top: 50%;
						left: 0;
						margin-left: 10px;
						transform: translateY(-50%);
					}
					/deep/ .van-card{
						display: flex;
						padding-left: 40px;
						align-items: flex-end;
						justify-content: space-between;
						margin: 0;
					}
					.delete-button{
						height: 100%;
					}
				}
			}
			/deep/ .van-submit-bar{
				bottom: 50px;
				.van-submit-bar__bar{
					justify-content: space-between;
				}
			}
		}
	}
</style>